<?php
class SiteDropDownList extends CWidget
{
    public function run()
    {
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
            $sites = CHtml::listData($sites, 'id', 'name');
        $defaultSiteId = FSM::run('Cms.site.getDefault')->id;
        if ($defaultSiteId==0)
        {
            $domain = parse_url(Yii::app()->request->getHostInfo(), PHP_URL_HOST);
            $domain = str_replace('.admin.','.',$domain);
            $siteUrlModel = SiteUrl::model()->find('url=:url AND status=true',array(':url'=>$domain));
            if (!is_null($siteUrlModel))
                $defaultSiteId = $siteUrlModel->site_id;    
        }
        echo CHtml::dropDownList('global_site', $defaultSiteId, $sites, array('style'=>'width: 200px;'));
        $script = "
        jQuery('#global_site').change(function(){
            jQuery.get('".$this->controller->createUrl('/Core/service/ajax', array('SID'=>'Cms.site.setCurrent'))."', {'site_id' : jQuery(this).val()}, function(data){
                var res = eval(data);
                window.location.href = res.admin_url;
            });
        });
        ";
        Yii::app()->clientScript->registerScript(__CLASS__.'#globalSite', $script, CClientScript::POS_READY);
    }
}